<?php
require_once(dirname(__FILE__) ."/DataObject.php");

/*
// Example:


//Creating PrivateMessage Object
$pm = new PrivateMessage();
$pm->setDBLink($dbLink);

$privateMessage->set("fromUserID"  => $user->getID(),
                  "fromGroupID" => $user->getIdentityGroupID(),
                  "subject"     => $_POST['subject'],
                  "body"        => $_POST['body']);

// Send messages to INBOX
if ($privateMessage->send())
{
    echo "Message delivered successfully.";
}
else
{
    echo $privateMessage->getErrorMessage();
}
*/


class PrivateMessageContact extends Core
{
    public $_dbContactsTable = 'privatemessages_contacts';
    public $_dbContactsUserIDField = 'userID';
    public $_dbContactsContactIDField = 'contact_userID';
    public $_dbUsersTable = 'users';
    public $_dbUsersUserIDField = 'userID';

    public function getByUserID($uid)
    {
        $sql = "SELECT pc.*, u.* FROM ". $this->_dbContactsTable ." AS pc, ". $this->_dbUsersTable ." AS u
                WHERE pc.". $this->_dbContactsUserIDField ."='". $uid ."'
                      AND pc.". $this->_dbContactsContactIDField ."=u.". $this->_dbUsersUserIDField ."
                ORDER BY u.alias";
        $this->_mysqlQuery($sql, $result);
        return $result;
    }

    public function update($uid, $contactsID)
    {
        if(!is_array($contactsID)) $contactsID = array($contactsID);

        $success=0;
        foreach($contactsID AS $contactID)
        {
            $sql = "UPDATE ". $this->_dbContactsTable ."
                   SET messages_count=messages_count+1, last_message=NOW()
                   WHERE ". $this->_dbContactsUserIDField ."='". $uid ."' AND ". $this->_dbContactsContactIDField ."='". $contactID ."'";
            if ($this->_mysqlQuery($sql, $result))
            {
                if (mysql_affected_rows($this->_dbLink)===0)
                {
                    $sql = "INSERT INTO ". $this->_dbContactsTable ." (userID, contact_userID, messages_count, first_message, last_message )
                           VALUES ('". $uid ."', '". $contactID ."', 1, NOW(), NOW())";
                    if ($this->_mysqlQuery($sql)) $success++;
                    // else No contact updated.
                }
                else $success++;
            }
            // else No contact updated.
        }
        return $success==count($contactsID);
    }

    public function delete($uid, $contactID)
    {
        $sql = "DELETE FROM ". $this->_dbContactsTable ." WHERE ". $this->_dbContactsUserIDField ."='". $uid ."' AND ". $this->_dbContactsContactIDField ."='". $contactID ."'";
        return $this->_mysqlQuery($sql);
    }
}

?>
